<?php
//连数据库
require('../../ht/Common/db.php');
session_start();
$pic = $_POST['pic'];
//上传文件错误的判定
if ($_FILES["pic"]["error"] > 0) {
    switch ($_FILES["pic"]["error"]) {
        case 1:
            echo "上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值";
            exit;
        case 3:
            echo "部分文件上传";
            exit;
        case 4:
            echo "没有选择海报!";
            break;
        default:
            echo "未知错误";
            exit;
    }
} else {   //上传文件正常，更新数据表
//2.上传文件判断类型
    $allowtype = array("jpg", "jpeg", "png", "gif", "bmp", "flv");
    $arr = explode(".", $_FILES["pic"]["name"]);
    $suffix = $arr[count($arr) - 1];
    if (!in_array($suffix, $allowtype)) {
        echo "文件类型错误！";
        exit;
    } else {
        echo "<br>头像已上传<br>";
    }
//3.拷贝文件
    $filepath = "../../images/user/";
    $randname = date("YmdHis") . "." . $suffix;
    move_uploaded_file($_FILES["pic"]["tmp_name"], $filepath . $randname);
    //获取原封面文件的文件名
    $sql = "select * from users where uname='{$_SESSION["user"]}'";
    $result = mysql_query($sql);
    $row = mysql_fetch_assoc($result);
    $filename = $filepath . $row["pic"];
    //删除原来的头像文件
    if (file_exists($filename))
        unlink($filename);
    //编写SQL语句
    $sql = "update users set pic='$randname' where uname='{$_SESSION["user"]}'";
}
//执行SQL语句
$result = mysql_query($sql) or die("sql={$sql}, 更新失败！<br/>" . mysql_error());
//判断是否更新成功
$num = mysql_affected_rows();//返回前一次 MySQL 操作所影响的记录行数
if ($num != 1) {
    echo "更新失败,2秒后返回个人中心";
    header("refresh:2;url='per_center.php'");
} else {
    header("location:per_center.php");
}
?>
